/**
 * 实时数据
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>实时数据</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.varIdName" placeholder="变量名称"></el-input>
      </el-form-item>
      <el-form-item>
      <el-input size="small" v-model="formInline.deviceName" placeholder="设备名称"></el-input>
      </el-form-item>
      <el-form-item>
      <el-input size="small" v-model="formInline.imei" placeholder="IMEI"></el-input>
      </el-form-item>
      <el-form-item >
        <el-select size="small" v-model="formInline.varReadWritable" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="formInline.projectId" placeholder="请选择">
          <el-option
            v-for="item in project_option"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <!-- <el-table-column align="center" type="selection" width="60">
      </el-table-column> -->
      <el-table-column sortable prop="status" label="状态" width="100">
        <template slot-scope="scope">
        <span v-if="scope.row.status==0"><img src="../../assets/img/red_point.png" width="32" height="32" /></span>
        <span v-if="scope.row.status==1"><img src="../../assets/img/green.png" width="32" height="32" /></span>
       </template>
      </el-table-column>
      <el-table-column sortable prop="varId" label="变量ID" width="100">
      </el-table-column>
      <el-table-column sortable prop="varName" label="变量名" width="100">
      </el-table-column>
      <el-table-column sortable prop="addressDisplay" label="IO连接" width="100">
      </el-table-column>
      <el-table-column sortable prop="varDataType" label="变量类型" width="100">
      </el-table-column>
      <el-table-column sortable  label="设备名称" width="150">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
          <p>IMEI: {{ scope.row.imei }}</p>
          <p>采集器名称: {{ scope.row.boxName }}</p>
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.deviceName }}</el-tag>
          </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column sortable prop="value" label="实时值" width="100">
        <template slot-scope="scope">
          {{ scope.row.value ==null ?  '--': scope.row.value}}
       </template>
      </el-table-column>
      <el-table-column sortable prop="readWritable" label="可读写性" width="100">
        <template slot-scope="scope">
          {{ scope.row.readWritable === 0 ?  '只读': '读写' }}
       </template>
      </el-table-column>
      <el-table-column sortable prop="time" label="上报时间" width="150">
         <template slot-scope="scope">
          {{ scope.row.time ==null ?  '--': scope.row.time}}
       </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" :disabled="scope.row.readWritable===0" @click="controlVariant(scope.$index, scope.row)">控制变量</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="variantFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="varForm" :rules="rules" ref="varForm">
        <el-form-item label="变量名称" prop="varName">
          <el-input size="small" v-model="varForm.varName" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="变量值" prop="varValue">
          <el-input size="small" v-model="varForm.varValue" auto-complete="off" placeholder="请输入控制值"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('varForm')">设置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {variantDataList,controlVariantValue} from '../../api/variantMG'
import{getProjectList} from '../../api/alarmMgr'
import Pagination from '../../components/Pagination'
export default {
  data() {
    return {
      loading: false, //是显示加载
      variantFormVisible:false,
      title:'控制变量',
      varForm:{
        varId:'',
        imei:'',
        varName:'',
        varValue:'',
        varDataType:''
      },
      // rules表单验证
      rules: {
        varValue: [{ required: true, message: '请输入变量值', trigger: 'blur' }]
      },
      formInline: {
        page: 1,
        limit: 10,
        varIdName: '',
        imei:'',
        projectId:0,
        varReadWritable:'',
      },
      project_option:[
        {
          value:0,
          label: '项目名称'
        }
      ],
      options: [{
          value: 0,
          label: '只读'
        }, {
          value: 1,
          label: '读写'
        }],
   
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      websock: null,
      lockReconnect:false
    }
  },
  // 注册组件
  components: {
    Pagination
  },


  /**
   * 创建完毕
   */
  created() {
    this.getProject();
    this.getdata(this.formInline)
  },

  mounted(){
    this.initWebSocket();
  },

  destroyed: function () { // 离开页面生命周期函数
      this.lockReconnect=false;
      this.websocketOnclose();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    getProject(){
      getProjectList({}).then(res=>{
          console.log("res",res)
          if (res.data.success == false) {
            this.$message({
              type: 'info',
              message: res.data.message
            })
          }else{
            let detailsList = res.data.result
            for (const i in detailsList) {
              this.project_option.push({
                value:detailsList[i].id,
                label:detailsList[i].name
              });  
            
            }
            console.log('option',this.project_option);
          }
      }).catch(err => {
          this.$message.error('获取项目列表失败，请稍后再试！')
        });
    },
    getdata(parameter) {
      this.loading = true
      variantDataList(parameter)
        .then(res => {
          console.log("res",res)
          this.loading = false
          if (res.data.success == false) {
            this.$message({
              type: 'info',
              message: res.data.message
            })
          } else {
            this.listData = res.data.result.list
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page
            this.pageparm.pageSize = this.formInline.limit
            this.pageparm.total = res.data.result.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取实时数据失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.formInline.page =1;
      this.getdata(this.formInline)
    },
    //显示发送控制变量界面
    controlVariant:function(index,row){
      this.variantFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.varForm.varName = row.varName
        this.varForm.varId = row.varId
        this.varForm.imei = row.imei
        this.varForm.varDataType = row.varDataType
        this.varForm.varValue = ''
      }
    },

    // 编辑、增加页面保存方法
    submitForm(varData) {
      this.$refs[varData].validate(valid => {
        if (valid) {
          controlVariantValue(this.varForm)
            .then(res => {
              this.variantFormVisible = false
              this.loading = false
              if (res.data.success) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '变量('+this.varForm.varName + ')写入值成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.data.message
                })
              }
            })
            .catch(err => {
              this.variantFormVisible = false
              this.loading = false
              this.$message.error('写入值失败，请稍后再试！')
            })
        } else {
          return false
        }
      })
    },
    // 关闭弹出框
    closeDialog() {
      this.variantFormVisible = false
    },

     initWebSocket: function () {
        var url = window._CONFIG['webSocketURL'] + '?token=' + sessionStorage.getItem('logintoken');
        //console.log(url);
        this.websock = new WebSocket(url);
        this.websock.onopen = this.websocketOnopen;
        this.websock.onerror = this.websocketOnerror;
        this.websock.onmessage = this.websocketOnmessage;
        this.websock.onclose = this.websocketOnclose;
      },

       websocketOnopen: function () {
        console.log("WebSocket连接成功");
        //心跳检测重置
        //this.heartCheck.reset().start();
      },

      websocketOnerror: function (e) {
        console.log("WebSocket连接发生错误");
        this.reconnect();
      },

      websocketOnmessage: function (e) {
        console.log("-----接收消息-------",e.data);
        var data = eval("(" + e.data + ")"); //解析对象
        if(data.msg_type === 1){
            this.renderRealData(data);
        }else if(data.msg_type === 2){
          this.renderPlcStatus(data);
        }else if(data.msg_type ===3){
          this.renderBoxStatus(data);
        }else {
          console.log("未知的数据格式",data);
        }
       
      },

      websocketOnclose: function (e) {
        console.log("connection closed (" + e + ")");
        if(e){
          console.log("connection closed (" + e.code + ")");
        }
        this.reconnect();
      },

      websocketSend(text) { // 数据发送
        try {
          this.websock.send(text);
        } catch (err) {
          console.log("send failed (" + err.code + ")");
        }
      },

      reconnect() {
        var that = this;
        if(that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
          console.info("尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },

      renderRealData(data){
        let dataIndex = [];
        let changeData = [];
        this.listData.forEach((item,i)=>{
          if(item.imei === data.imei){
              changeData.push(item.varId);
              dataIndex.push(i);
          }
        });
        changeData.forEach((item,i)=>{
            if(data.hasOwnProperty(String(item))){
              this.listData[dataIndex[i]].value =  String(data[String(item)]);
              this.listData[dataIndex[i]].time = this.timestampToTime(data.time);
              
              if(this.listData[dataIndex[i]].value == ''){
                this.listData[dataIndex[i]].status = 0;
              }else{
                this.listData[dataIndex[i]].status = 1;
              }
            }
        });
      },

      renderPlcStatus(data){
        let indexData = [];
        let changeData = [];
        this.listData.forEach((item,i)=>{
          if(item.imei === data.imei){
            if(data.hasOwnProperty(String(item.deviceId))){
              indexData.push(i);
              changeData.push(String(item.deviceId));
            }
          }
        });
        changeData.forEach((deviceId,i)=>{
            if(data.hasOwnProperty(deviceId)){
              this.listData[indexData[i]].status = data[deviceId];
            }
        });

      },

      renderBoxStatus(data){
        if(data.status === 0){ // 只有离线的时候，把在线状态换成离线
          this.listData.forEach(item=>{
            if(item.imei === data.imei && item.status === 1){
                item.status = 0;
            }
          });
        }
      },

      timestampToTime (time) {
        var date = new Date(time) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-'
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
        var D = (date.getDate() < 10 ? '0'+ date.getDate() : date.getDate()) + ' '
        var h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':'
        var m = (date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes()) + ':'
        var s = date.getSeconds() < 10 ? '0'+ date.getSeconds() : date.getSeconds()
        return Y+M+D+h+m+s
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 
 